package com.hardson.toolkit.swing.jbutton;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.Icon;
import javax.swing.JButton;

import com.hardson.toolkit.swing.GradientColor;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

public class RoundCornerButton extends JButton {

	private static final long serialVersionUID = 1L;

	@Getter
	@Setter
	protected GradientColor bgColor = null;

	@Getter
	@Setter
	@Accessors(chain = true)
	protected Color borderColor = Color.LIGHT_GRAY;

	@Getter
	@Setter
	protected Dimension arc = new Dimension(4, 4);

	public RoundCornerButton(final String text, final Icon icon, final Dimension arc) {
		super(text, icon);
		if (arc != null) {
			this.arc = arc;
		}
		//this.setPreferredSize(new Dimension(250, 80));
		this.bgColor = GradientColor.of(this.getBackground(), this.getBackground());
		this.setFocusPainted(false);// 去掉 点击按钮时，文本周边的虚线
		this.setContentAreaFilled(false);// 按钮本身设置为透明，只有这样才能显示出我们自己定义的颜色，此方法调用会把opaque变为false
	}

	@Override
	public void paintComponent(final Graphics g) {// 绘制填充按钮的形状：圆角矩形按钮
		if (this.isEnabled() && this.bgColor != null) {
			Dimension size = this.getSize();
			Graphics2D g2d = (Graphics2D) g;
			// 以下两句，是消除圆角周边的锯齿用的
			RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			g2d.addRenderingHints(rh);

			// 设置填充按钮的渐变颜色
			GradientPaint paint = new GradientPaint(0, 0, this.bgColor.getStartColor(), 0, size.height - 1,
					this.bgColor.getEndColor());
			g2d.setPaint(paint);// 设置绘图对象的填充模式

			// 设置填充圆角矩形区域

			//			if (this.isBorderPainted()) {
			//				g2d.fillRoundRect(1, 1, size.width - 2, size.height - 2, 4, 4);
			//			} else {
			g2d.fillRoundRect(0, 0, size.width - 1, size.height - 1, this.arc.width, this.arc.height);
			//}
		}
		super.paintComponent(g);
	}

	/**
	 * 绘制按钮边框：圆角矩形边框
	 */
	@Override
	public void paintBorder(final Graphics g) {
		if (!this.isBorderPainted()) {
			return;
		}
		g.setColor(this.isEnabled() ? this.borderColor : Color.LIGHT_GRAY);
		// 画边界区域
		Dimension size = this.getSize();
		g.drawRoundRect(0, 0, size.width - 1, size.height - 1, this.arc.width, this.arc.height);
	}

}
